package com.styles.codingstyle.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Package com.styles.codingstyle.aspect
 * @Description: 统一异常处理拦截日志
 * @Author 陈建
 * @Create: 2018-05-30 16:34
 * @Version 1.0
 * @Update: message
 */
@Aspect
@Component
public class ExceptionHandleAspect {
    private final static Logger logger = LoggerFactory.getLogger(ExceptionHandleAspect.class);

    @Pointcut("execution(public * com.styles.codingstyle.Handle.*.*(..))")
    public void log() {
    }

    @Before("log()")
    public void doExceptionHandleBeforeLog(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        logger.warn("RequestTime={} IP={} Method={} Url={} Args={} Class_Method={}", System.currentTimeMillis(), request.getRemoteAddr(), request.getMethod(), request.getRequestURL(), joinPoint.getArgs(), joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());

        // logger.warn("Signature={}", joinPoint.getSignature());
        //logger.warn("Kind={}", joinPoint.getKind());
        // logger.warn("SourceLocation={}", joinPoint.getSourceLocation());
        //logger.warn("Target={}", joinPoint.getTarget());

    }

    @AfterReturning(returning = "object", pointcut = "log()")
    public void doExceptionHandleAterReturning(Object object) {

        logger.warn("EndTime={} Response={}", System.currentTimeMillis(), object.toString());
        //logger.info("Response={}", object.toString());
    }

}
